<!-- 订单确认 -->
<template>
  <div v-loading="loading">
    <div class="title_bold gl_mb_15">
      <span>核对订单信息</span>
      <span class="car_style" @click="toShoppingCart">修改购物车</span>
    </div>
    <div class="settlement box gl_mb_20">
      <p class="title gl_ml_20 gl_pt_15">收款方：{{ orderData.storeName }}</p>
      <el-table ref="table" class="gl_table_noBorder gl_mb_5" :data="orderData.items" size="mini">
        <el-table-column :width="30" />
        <el-table-column label="商品名称">
          <template slot-scope="{ row }">
            <div>
              <div class="img_box gl_dis_ib gl_middle">
                <img :src="getStaticPhotoUrl(row.imageUrl)" alt="" style="width:100%; height:100%">
              </div>
              <div class="gl_dis_ib gl_middle gl_mx_10 gl_pointer hover_name" style="width: 560px" @click="toStore(orderData.storeId, row.productId)">{{ row.productName }}</div>
              <div class="gl_dis_ib gl_middle">{{ row.color }} {{ row.size }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价/数量" :width="160">
          <template slot-scope="{ row }">
            <p>¥{{ (row.price / 100).toFixed(2) }}</p>
            <p>X{{ row.count }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="小计" :width="160">
          <template slot-scope="{ row }">
            ¥{{ (row.amount / 100).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="box gl_mb_20">
      <el-row type="flex" justify="space-between" class="title gl_pt_15">
        <el-col :span="20">
          <p class="gl_ml_20">收货人信息</p>
        </el-col>
        <el-col :span="3" align="right">
          <p class="gl_pr_20 gl_mr_10 gl_fs_14 gl_ft_weight gl_pointer" @click="addAddress">新增收货地址</p>
        </el-col>
      </el-row>
      <div v-if="addressData.length > 0" v-loading="addressLoading" class="address">
        <ul>
          <el-scrollbar wrap-class="scrollbar-wrapper scrollbar" :class="[ addressData.length > 6 ? 'scroll_height': '' ]">
            <li v-for="(item, index) in addressData" :key="item.id" :class="[ addressData.length - 1 == index ? 'gl_mb_10': '' ]">
              <el-row type="flex" justify="space-between">
                <el-col :span="18">
                  <div class="left_div">
                    <div class="name gl_ellipsis" :class="[ index == selectIndex ? 'default': 'no_default' ]" :title="item.consigneeName" @click="selectAddress(index)">{{ item.consigneeName }}</div>
                    <div style="width: 500px" class="gl_ml_15 gl_ellipsis" :title="`${addressDataForCheck(item.provinceCode, item.cityCode, item.countyCode)} ${item.address}`">{{ addressDataForCheck(item.provinceCode, item.cityCode, item.countyCode) }} {{ item.address }}</div>
                    <div class="gl_ml_10">{{ handlePhoneNumber(item.phoneNumber) }}</div>
                    <div v-if="item.isDefault" class="default_tag">默认地址</div>
                  </div>
                </el-col>
                <el-col :span="5" align="right">
                  <div class="right_div">
                    <div v-if="!item.isDefault" class="gl_ml_10" @click="removeAddress(item.id)">删除</div>
                    <div @click="editAddress(item)">编辑</div>
                    <div v-if="!item.isDefault" class="gl_mr_10" @click="clickDefault(item.id)">设置默认地址</div>
                  </div>
                </el-col>
              </el-row>
            </li>
          </el-scrollbar>
        </ul>
      </div>
      <div v-if="addressDataCopy.length > 1" class="control" @click="showMore">
        <template v-if="!isShowMore">
          <i class="el-icon-arrow-down" />
          <span class="gl_pl_10 control_text">展开列表</span>
        </template>
        <template v-else>
          <i class="el-icon-arrow-up" />
          <span class="gl_pl_10 control_text">收起列表</span>
        </template>
      </div>
    </div>
    <AddAndEdit ref="addAndEdit" />
    <div class="amount">
      <div class="gl_mb_15">
        <span class="gl_fs_14">应付总额：</span>
        <span class="gl_fs_12 red">¥</span>
        <span style="font-size: 18px" class="red gl_ft_weight">{{ (orderData.amount / 100).toFixed(2) }}</span>
      </div>
      <el-button type="danger" @click="clickPay">
        <span>提交订单</span>
      </el-button>
    </div>

    <!-- 选择支付方式弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
    </el-dialog>

    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import AddAndEdit from '@/components/Address/addAndEdit';
import OfflinePayInfo from '@/components/OfflinePayInfo';
import {
  api_GET_MallStoreId, // 店铺信息
  api_POST_MallReceiptCheckReceiptFromShoppingCart, // 从购物车跳转获取核定订单信息
  api_POST_MallReceiptCheckReceiptFromProduct, // 从商品详情页跳转获取订单核对信息
  api_GET_MallDeliveryAddress, // 获取收货地址
  api_DELETE_MallDeliveryAddressId, // 删除收货地址
  api_POST_MallDeliveryAddressIdSetDefault, // 设为默认
  api_GET_MallReceiptStorePayInfoStoreId, // 获取商城店铺设置的支付信息
  api_POST_MallReceiptPlaceOrders // 下单
} from '@/extend/api/shoppingmallswaggerApi/app.js';
import {
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';
import {
  Api_GET_MallDeliveryAddressQO, // 获取收货地址
  SiSTKWMallPlaceOrdersInput // 下单
} from '@/lib/form/shoppingmall/swaggerForm.js';
import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';
export default {
  components: {
    AddAndEdit, // 新增 or 编辑地址
    OfflinePayInfo
  },
  data() {
    return {
      loading: false,
      addressLoading: false,
      registerId: '',
      orderData: [],
      isShowMore: false, // 是否展示更多地址
      getAddressQO: new Api_GET_MallDeliveryAddressQO(),
      addressData: [], // 渲染的地址列表
      addressDataCopy: [], // 所有的地址列表
      selectIndex: 0, // 选中的地址
      payForm: new SiSTKWMallPlaceOrdersInput(),
      payInfo: {},
      dialogVisibleForPay: false, // 选择支付方式弹窗
      isOnlinePayment: true, // 是否是线上支付
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      modalPayLoding: false,
      offlineDialogVisible: false,
      offlineData: {},
      orderNo: '' // 订单编号
    };
  },
  computed: {
    ...mapState({
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      settlementGoods: state => state.app.settlementGoods,
      buyGoods: state => state.app.buyGoods
    })
  },
  watch: {
    'UserType': {
      immediate: true,
      deep: true,
      handler(val, old) {
        old = old || {};
        if (val && val.registerId && val.registerId !== old.registerId) {
          this.registerId = val.registerId;
        }
      }
    }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    this.getOrderData();
    this.getAddress();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取订单信息
    getOrderData() {
      var that = this;
      that.loading = true;
      if (that.$route.query.last && that.$route.query.last === 'shoppingCart') {
        let shoppingCartIds = that.settlementGoods;
        if (shoppingCartIds.length > 0) {
          const copyShoppingCartIds = JSON.stringify(shoppingCartIds);
          sessionStorage.setItem('settlementGoods', copyShoppingCartIds);
        } else {
          shoppingCartIds = JSON.parse(sessionStorage.getItem('settlementGoods'));
        }
        // 从购物车过来
        const form = {
          shoppingCartIds: shoppingCartIds
        };
        api_POST_MallReceiptCheckReceiptFromShoppingCart(form).then(res => {
          that.orderData = res || {};
          that.orderData.amount = that.orderData && that.orderData.amount ? that.orderData.amount : 0;
          if (that.orderData.storeId) {
            that.hasPayWay(that.orderData.storeId);
          }
          that.loading = false;
        }, error => {
          that.loading = false;
          that.$message({ type: 'error', message: '获取数据失败！' + (error.error && error.error.message || '') });
        });
      } else {
        let data = that.buyGoods;
        if (data.productId) {
          const copyData = JSON.stringify(data);
          sessionStorage.setItem('setBuyGoods', copyData);
        } else {
          data = JSON.parse(sessionStorage.getItem('setBuyGoods'));
        }
        // 从商品详情过来
        const form = {
          count: data.count,
          productId: data.productId,
          colorName: data.color && data.color.name,
          sizeName: data.size && data.size.name
        };
        api_POST_MallReceiptCheckReceiptFromProduct(form).then(res => {
          that.orderData = res || {};
          that.orderData.amount = that.orderData && that.orderData.amount ? that.orderData.amount : 0;
          if (that.orderData.storeId) {
            that.hasPayWay(that.orderData.storeId);
          }
          that.loading = false;
        }, error => {
          that.loading = false;
          that.$message({ type: 'error', message: '获取数据失败！' + (error.error && error.error.message || '') });
        });
      }
    },
    // 获取地址列表
    getAddress() {
      // if (!this.registerId) return;
      const that = this;
      this.addressLoading = true;
      // this.getAddressQO.RegisterId = this.registerId;
      this.getAddressQO.MaxResultCount = 15;
      api_GET_MallDeliveryAddress(this.getAddressQO).then(res => {
        that.addressDataCopy = res || [];
        if (that.addressDataCopy && that.addressDataCopy.length > 0) {
          that.addressData = [that.addressDataCopy[0]];
        } else {
          that.addressData = [];
        }
        that.selectIndex = 0;
        that.addressLoading = false;
      }, error => {
        that.addressLoading = false;
        that.$message({ type: 'error', message: '获取地址列表失败！' + (error.error && error.error.message || '') });
      });
    },
    // 新增地址
    addAddress() {
      if (this.addressDataCopy.length < 15) {
        const title = '新增收货地址';
        // this.$refs.addAndEdit.open(title, this.registerId);
        this.$refs.addAndEdit.open(title);
      } else {
        this.$message({ type: 'warning', message: '最多可创建15条地址，现已超出，不可创建' });
      }
    },
    // 编辑地址
    editAddress(item) {
      const title = '编辑收货地址';
      // this.$refs.addAndEdit.open(title, this.registerId, item);
      this.$refs.addAndEdit.open(title, item);
    },
    // 设为默认地址
    clickDefault(id) {
      const that = this;
      this.addressLoading = true;
      api_POST_MallDeliveryAddressIdSetDefault(id).then(res => {
        that.addressLoading = false;
        that.getAddress();
        that.isShowMore = false;
      }, error => {
        that.addressLoading = false;
        that.$message({ type: 'error', message: '设置默认地址失败！' + (error.error && error.error.message || '') });
      });
    },
    // 选中的地址
    selectAddress(index) {
      // this.selectIndex = index;
      this.addressDataCopy.unshift(this.addressDataCopy.splice(index, 1)[0]);
      this.showMore();
    },
    // 删除地址
    removeAddress(id) {
      const that = this;
      this.$confirm(`您确定要删除此地址吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // if (!that.registerId) return;
        api_DELETE_MallDeliveryAddressId(id).then(res => {
          that.$message({ type: 'success', message: '删除成功' });
          that.getAddress();
          that.isShowMore = false;
        }, error => {
          that.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
        });
      }).catch(() => {});
    },
    // 处理省市区
    addressDataForCheck (_provinceCode, _cityCode, _countyCode) {
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      _provinceData = _provinceData ? _provinceData.name : '';
      _cityData = _cityData ? _cityData.name : '';
      _countyData = _countyData ? _countyData.name : '';
      return `${_provinceData} ${_cityData} ${_countyData}`;
    },
    // 处理电话号码
    handlePhoneNumber (phone) {
      const str1 = phone.substr(0, 3);
      const str2 = phone.substr(7, 4);
      return str1 + '****' + str2;
    },
    // 地址列表的展开收起
    showMore() {
      this.isShowMore = !this.isShowMore;
      if (this.isShowMore) {
        this.addressData = this.addressDataCopy;
      } else {
        this.addressData = [this.addressDataCopy[0]];
      }
    },
    // 去往购物车
    toShoppingCart() {
      if (this.$route.path.indexOf('myCenter') !== -1) {
        const href = `${location.origin}/mycenter.html#/myCenter/mall/shoppingCart`;
        window.location.href = href;
      } else {
        this.$router.push({
          name: 'MyCart'
        });
      }
    },
    // 去往店铺商品
    toStore(storeId, productId) {
      api_GET_MallStoreId(storeId).then(res => {
        const store = res;
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.href = `${location.origin}/mall.html#/home/${store.route + (store.tenantId ? '_' + store.tenantId : '') + '_plat'}/info/${productId || ''}`;
        a.target = '_blank';
        a.dispatchEvent(event);
      });
    },
    // 获取商家设置的支付方式
    hasPayWay (storeId) {
      var that = this;
      api_GET_MallReceiptStorePayInfoStoreId(storeId).then(res => {
        that.payInfo = res || {};
      }, (error) => {
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 点击支付按钮
    clickPay () {
      if (this.addressDataCopy.length < 1 || (!this.addressDataCopy[this.selectIndex].consigneeName)) {
        this.$message({ type: 'warning', message: '请设置收货地址' });
        return;
      }
      // 请注意代码顺序不可调整
      const _setOnline = this.payInfo.isOpenOnlinePay; // 设置了线上支付
      const _setOffline = this.payInfo.isOpenOfflinePay; // 设置了线下支付
      // 当同时设置了线上与线下支付时，弹窗让用户选择支付方式
      if (_setOnline && _setOffline) {
        this.dialogVisibleForPay = true;
        return;
      }
      // 仅设置了线上支付
      if (_setOnline) {
        this.clickPayOnline();
        return;
      }
      // 仅设置了线下支付
      if (_setOffline) {
        this.clickPayOffline();
        return;
      }

      if (!_setOnline && !_setOffline) {
        this.$message({ type: 'error', message: '无法提交订单，请联系商家！' });
      }
    },
    // 线上支付
    clickPayOnline () {
      this.isOnlinePayment = true; // 是否是线上订单
      this.submitOrder();
    },
    // 线下支付
    clickPayOffline () {
      this.isOnlinePayment = false; // 是否是线上订单
      this.submitOrder();
    },
    // 提交订单
    submitOrder() {
      var that = this;
      that.modalPayLoding = true;
      that.payForm.registerId = that.registerId;
      that.payForm.storeId = that.orderData.storeId;
      that.payForm.isOnlinePayment = that.isOnlinePayment;
      const address = that.addressDataCopy[that.selectIndex];
      that.payForm.consigneeName = address.consigneeName;
      that.payForm.phoneNumber = address.phoneNumber;
      that.payForm.address = that.addressDataForCheck(address.provinceCode, address.cityCode, address.countyCode) + ' ' + address.address;
      that.payForm.receiptInputs = that.orderData.items;
      api_POST_MallReceiptPlaceOrders(that.payForm).then(res => {
        that.orderNo = res.orderNo;
        if (that.isOnlinePayment) {
        // 如果是线上支付
          that.payment(res.orderNo);
        } else {
        // 线下支付，展示获取订单信息，展示收款账户信息
          that.getOrderDetails(res.orderNo);
        }
        that.modalPayLoding = false;
      }).catch(error => {
        that.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
        that.modalPayLoding = false;
      });
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo }).then(res => {
        res._orderNo = orderNo;
        this.offlineData = res;
        this.offlineDialogVisible = true;
      }).catch(error => {
        this.$message({ type: 'error', message: `订单详情获取失败！${error.error.message}` });
      });
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = '/mycenter.html';
        const _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    // 跳转到订单中心
    jumpToOrderCenter () {
      const _origin = window.location.origin;
      const _pathname = '/mycenter.html';
      const _orderUrl = '#/myCenter/order/main?out_trade_no=' + this.orderNo;
      const url = _origin + _pathname + _orderUrl;
      if (this.$route.params.id) {
        this.$router.push({
          path: `/home/${this.$route.params.id}`
        });
      }
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = url;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 获取图片地址
    getStaticPhotoUrl(relativeUrl) {
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style scoped>
.title_bold {
  font-weight: 600;
  color: #353434;
  font-size: 20px;
  padding-left: 5px;
  padding-top: 50px;
}
.car_style {
  font-weight: 400;
  color: #666;
  font-size: 14px;
  padding-left: 15px;
  padding-top: 50px;
  cursor: pointer;
}
.car_style:hover{
  text-decoration: underline;
}
.box {
  border-radius: 8px;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
  padding: 5px 0 0 12px;
}
.title {
  font-size: 14px;
  font-weight: 500;
  color: #353434;
  padding-bottom: 10px;
}
.el-table,.el-table /deep/ .el-table__body-wrapper {
  min-height: auto;
}
.settlement .el-table {
  border-right: none !important;
  border-left: none;
}
.img_box {
  width: 62px;
  height: 62px;
  overflow: hidden;
}
.address{
  margin-top: 30px;
  border-top: 1px solid #e8e8e8;
  margin-right: 12px;
}
.address li {
  height: 58px;
  padding: 12px 0;
  padding-left: 20px;
  font-size: 14px;
  border-bottom: 1px solid #e8e8e8;
}
.address li .left_div div{
  float: left;
  height: 34px;
  line-height: 34px;
}
.address li .right_div {
  padding-right: 30px;
}
.address li .right_div div{
  float: right;
  height: 34px;
  line-height: 34px;
  color: #bdbdbd;
  cursor: pointer;
}
.address li .name {
  width: 94px;
  padding: 0 4px;
  border-radius: 2px;
  text-align: center;
  cursor: pointer;
}
.no_default {
  border: 1px solid #cccccc;
  color: #cccccc;
}
.default {
  border: 1px solid #e33a3c;
  color: #e33a3c;
}
.default_tag {
  margin-left: 12px;
  width: 76px;
  height: 28px;
  background: #e33a3c;
  border-radius: 2px;
  color: #fff;
  text-align: center;
}
.control {
  text-align: center;
  line-height: 38px;
  margin-right: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all .2s;
}
.control_text {
  font-size: 14px;
  display: none;
}
.control:hover .control_text {
  display: inline-block;
  color: #409eff;
  transition: all .2s;
}
.control:hover{
  color: #409eff;
  background: #f9fafc;
  transform: translateX(-20px);
}
.amount {
  margin: 40px 40px 72px 0;
  text-align: right;
  line-height: 22px;
}
.red {
  color: #ff3434;
}
.el-button--danger {
  width: 160px;
  background-color: #e33a3c;
  border-color: #e33a3c;
}

.pay_type_list {
  display: flex;
  justify-content: space-around;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_online {
  background-image: url('../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}
.pay_btn {
  border-radius: 8px;
  background: #ff704a;
  border-color: #ff704a;
}
.hover_name:hover {
  color: #1B5CFF;
}
.el-scrollbar /deep/ .el-scrollbar__wrap{
  overflow-x: hidden;
  padding-bottom: 10px;
}
.scrollbar {
  width: 100%;
}
.scroll_height {
  height: 350px;
}
</style>
